package com.dries.security.app.service.impl;

import cn.hutool.core.util.StrUtil;
import com.dries.security.core.validate.code.captcha.SysCaptcha;
import com.dries.security.core.validate.code.captcha.enums.ValidateCodeType;
import com.dries.security.core.validate.code.exception.ValidateCodeException;
import com.dries.security.core.validate.code.impl.ValidateCodeMapper;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.ServletWebRequest;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Classname RedisValidateCodeRepository
 * @Description TODO
 * @Date 2019/11/24 20:22
 * @Author ZSY
 */
@Component
public class RedisValidateCodeServiceImpl implements ValidateCodeMapper {

    @Resource
    private RedisTemplate<Object, Object> redisTemplate;

    /***
     * @Description: save 保存验证码
     * @param: [request, code, validateCodeType]
     * @return: void
     * @date: 2019/11/24 18:36
     *
     * @param request
     * @param code
     * @param validateCodeType*/
    @Override
    public void save(ServletWebRequest request, SysCaptcha code, ValidateCodeType validateCodeType) {
        redisTemplate.opsForValue().set(buildKey(request, validateCodeType), code, 60, TimeUnit.MINUTES);
    }

    /***
     * @Description: get 获取验证码
     * @param: [request, validateCodeType]
     * @return: com.zsycms.security.core.validate.code.ValidateCode
     * @date: 2019/11/24 18:37
     *
     * @param request
     * @param validateCodeType*/
    @Override
    public SysCaptcha get(ServletWebRequest request, ValidateCodeType validateCodeType) {
        Object value = redisTemplate.opsForValue().get(buildKey(request, validateCodeType));
        if (value == null) {
            return null;
        }

        return (SysCaptcha) value;
    }

    /***
     * @Description: remove 移除验证码
     * @param: [request, validateCodeType]
     * @return: void
     * @date: 2019/11/24 18:39
     *
     * @param request
     * @param validateCodeType*/
    @Override
    public void remove(ServletWebRequest request, ValidateCodeType validateCodeType) {
        redisTemplate.delete(buildKey(request, validateCodeType));
    }

    private String buildKey(ServletWebRequest request, ValidateCodeType codeType) {

        String deviceId = request.getHeader("deviceId");

        if (StrUtil.isBlank(deviceId)){
            throw new ValidateCodeException("请在请求头中携带deviceId参数");
        }

        return "code:" + codeType.toString().toLowerCase() + ":" + deviceId;
    }
}
